package cron

import (
	"fmt"

	"github.com/modood/table"
	"github.com/robfig/cron/v3"

	"gin-api-server/app"
	"gin-api-server/core_library/global"
)

func InitCron() {
	// 计划任务
	status := global.Config.Timer.STATUS
	if !status {
		return
	}

	type lk struct {
		Name, Time     string
		RegisterStatus string
		ErrorMessage   string
	}
	var runtask = make([]lk, 0)

	c := cron.New(cron.WithSeconds())
	for _, task := range app.RegisterTimers() {
		_, err := c.AddFunc(task.Time, task.Func)
		errorMessage := ""
		registerStatus := "Success"
		if err != nil {
			errorMessage = err.Error()
			registerStatus = "Error"
		}
		runtask = append(runtask, lk{
			Name:           task.Name,
			Time:           task.Time,
			RegisterStatus: registerStatus,
			ErrorMessage:   errorMessage,
		})
	}
	if len(runtask) > 0 && global.Config.Timer.ShowList {
		fmt.Println("计划任务列表")
		table.Output(runtask)
	}

	c.Start()
}
